package com.waiter.moximoxi.ui;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;
import com.waiter.moximoxi.R;
import com.waiter.moximoxi.adapter.OrderInfoDiscountAdapter;
import com.waiter.moximoxi.base.BaseActivity;
import com.waiter.moximoxi.bean.CouponUserInfo;
import com.waiter.moximoxi.bean.OrderInfoBean;
import com.waiter.moximoxi.bean.OrderInfoDiscountListBean;
import com.waiter.moximoxi.bean.UserConponBean;
import com.waiter.moximoxi.bean.VipCardPayBean;
import com.waiter.moximoxi.constant.Constant;
import com.waiter.moximoxi.dialog.CollectionDialog;
import com.waiter.moximoxi.dialog.CouponInfoDialog;
import com.waiter.moximoxi.dialog.SearchHistoryDeleteDialog;
import com.waiter.moximoxi.dialog.SettlementOrderDialog;
import com.waiter.moximoxi.net.API;
import com.waiter.moximoxi.presenter.Constants;
import com.waiter.moximoxi.presenter.IPrinterPresenter;
import com.waiter.moximoxi.presenter.PrinterPresenterImpl;
import com.waiter.moximoxi.utils.DateUtils;
import com.waiter.moximoxi.utils.JsonTwoUtils;
import com.waiter.moximoxi.utils.KeyBoardHideShowUtils;
import com.waiter.moximoxi.utils.PrintUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import cn.com.sand.hmpay.HmpayClient;
import cn.com.sand.hmpay.contants.TradeContants;
import cn.com.sand.hmpay.util.RsaUtil;
import cn.com.sand.hmpay.vo.request.TradeRequest;
import cn.com.sand.hmpay.vo.request.biz.TradeRefundRequest;
import cn.com.sand.hmpay.vo.response.TradeResponse;
import cn.yhong.aframework.listener.DefaultHintDialogListener;
import cn.yhong.aframework.listener.OkHttpSuccessListener;
import cn.yhong.aframework.listener.OnCallbackListener;
import cn.yhong.aframework.utils.AtyUtils;
import cn.yhong.aframework.utils.MyOkHttpUtils;
import cn.yhong.aframework.view.IBaseView;
import okhttp3.Call;

/**
 * Created by 17639 on 2020/10/14.
 */

public class SettlementActivity extends BaseActivity implements View.OnClickListener, OrderInfoDiscountAdapter.OnDiscountClickListener {

    @Bind(R.id.back_tv)
    TextView back_tv;
    @Bind(R.id.coupon_reset)
    TextView coupon_reset;
    @Bind(R.id.table_num)
    TextView table_num;
    @Bind(R.id.table_time)
    TextView table_time;
    @Bind(R.id.table_price)
    TextView table_price;
    @Bind(R.id.table_people_count)
    TextView table_people_count;
    @Bind(R.id.vip_score)
    TextView vip_score;
    @Bind(R.id.vip_phone)
    TextView vip_phone;
    @Bind(R.id.coupon_tv)
    TextView coupon_tv;
    @Bind(R.id.coupon_info_tv)
    TextView coupon_info_tv;
    @Bind(R.id.detailed_tv)
    TextView detailed_tv;
    @Bind(R.id.remove_zero_tv)
    EditText remove_zero_tv;
    @Bind(R.id.old_price)
    TextView old_price;
    @Bind(R.id.consume_details_tv)
    TextView consume_details_tv;
    @Bind(R.id.coupon_price)
    TextView coupon_price;
    @Bind(R.id.need_pay_price)
    TextView need_pay_price;
    @Bind(R.id.already_pay_price)
    TextView already_pay_price;

    @Bind(R.id.vip_card)
    TextView vip_card;
    @Bind(R.id.print_order_bill)
    TextView print_order_bill;
    @Bind(R.id.ali_tv)
    TextView ali_tv;
    @Bind(R.id.wx_tv)
    TextView wx_tv;
    @Bind(R.id.pay_by_card_tv)
    TextView pay_by_card_tv;

    @Bind(R.id.print_jiesuan_ticket)
    TextView print_jiesuan_ticket;

    @Bind(R.id.scrollView)
    ScrollView scrollView;
    @Bind(R.id.order_info_recyclerview)
    RecyclerView order_info_recyclerview;

    private SettlementOrderDialog settlementOrderDialog;//消费明细弹框
    private CouponInfoDialog couponInfoDialog;//优惠券明细弹框
    private CollectionDialog collectionDialog;//支付金额弹框

    public static final int DEFAULT_VIEW = 0x22;
    private static final int REQUEST_CODE_SCAN = 0X01;

    private String order_sn;//订单编号

    private List<UserConponBean> userConponBeans;
    private OrderInfoBean orderInfoBean;

    private int scren_type;//扫码类型
    private String need_pay_last_money_nomoling = "0";//不抹零最终需要付的钱
    private String dialog_set_pay_money = "0";//弹框设置收取的钱
    private boolean is_moling;//是否抹零
    private String jifen_code = "";//积分码
    private boolean isOrderFinish;//订单是否支付完成
    private String isPay;//是否支付

    private OrderInfoDiscountAdapter orderInfoDiscountAdapter;
    private List<OrderInfoDiscountListBean> discounts;//折扣数据列表

    private IPrinterPresenter presenter;
    private List<Object> printer_templete;//打印小票数据

    private String discount_id = "0";//折扣id
    private String is_member = "0";//是否扫取会员码 1已扫取 0未扫取

    @Override
    public void initIntent(Intent intent) {
        order_sn = intent.getStringExtra("order_sn");
    }

    @Override
    public void initContent(Bundle savedInstanceState) {
        setContent(R.layout.activity_settlement);
    }

    @Override
    public void initView() {
        // 广播监听
        if (broadcastManager == null) {
            broadcastManager = LocalBroadcastManager.getInstance(this);
        }
        if (intentFilter == null) {
            intentFilter = new IntentFilter();
        }
        intentFilter.addAction(ACTION_RECIVE_NEWRED);
        if (receiver == null) {
            receiver = new SettlementReceiver();
        }
        broadcastManager.registerReceiver(receiver, intentFilter);

        detailed_tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
    }

    @Override
    public void initData() {
        setHintKeyboardView(scrollView);
        //键盘消失操作
        KeyBoardHideShowUtils.setListener(mActivity, new KeyBoardHideShowUtils.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {

            }

            @Override
            public void keyBoardHide(int height) {
                if (!TextUtils.isEmpty(AtyUtils.getText(remove_zero_tv))) {//输入值不为空
                    if (Integer.valueOf(AtyUtils.getText(remove_zero_tv)) > Integer.valueOf(orderInfoBean.order_moling)) {//输入金额大于最大抹零金额
                        remove_zero_tv.setText("");
                        Moling("");
                        AtyUtils.showShort(mActivity, "抹零上限是" + orderInfoBean.order_moling, false);
                    } else {
                        Moling(AtyUtils.getText(remove_zero_tv));
                    }
                } else {
                    Moling("");
                }
            }
        });

        discounts = new ArrayList<>();
        printer_templete = new ArrayList<>();
        userConponBeans = new ArrayList<>();


        orderInfoDiscountAdapter = new OrderInfoDiscountAdapter(0, discounts);
        orderInfoDiscountAdapter.setOnDiscountClickListener(this);
        //设置主轴方向为横轴
        FlexboxLayoutManager manager = new FlexboxLayoutManager(mActivity, FlexDirection.ROW);
        //设置item沿主轴方向的位置
        manager.setJustifyContent(JustifyContent.FLEX_START);
        //设置item 沿次轴方向的位置
        manager.setAlignItems(AlignItems.CENTER);
        order_info_recyclerview.setLayoutManager(manager);
        order_info_recyclerview.setAdapter(orderInfoDiscountAdapter);


        //账单明细
        settlementOrderDialog = new SettlementOrderDialog(mActivity);

        //优惠券
        couponInfoDialog = new CouponInfoDialog(mActivity, new OnCallbackListener() {
            @Override
            public void onCallback(int type, Object... obj) {
                int position = (int) obj[0];
                UserConponBean userConponBean = (UserConponBean) obj[1];
                if (!TextUtils.isEmpty(isPay) && isPay.equals("1")) {
                    AtyUtils.showShort(mActivity, "订单已支付，优惠券不可取消", true);
                    return;
                }
                cancelCoupon(userConponBean.card_id, position);
            }
        });

        //收款
        collectionDialog = new CollectionDialog(mActivity, new OnCallbackListener() {
            @Override
            public void onCallback(int type, Object... obj) {
                dialog_set_pay_money = (String) obj[0];
                if (scren_type == 4) {//支付宝
                    newViewBtnClick();

                } else if (scren_type == 5) {//微信
                    newViewBtnClick();

                } else if (scren_type == 6) {//刷卡

                    int length = dialog_set_pay_money.length();
                    String price_add = "";
                    for (int i = 0; i < 10 - length; i++) {
                        price_add += "0";
                    }

                    AtyUtils.i("金额", price_add + dialog_set_pay_money);

                    Intent intent = new Intent();
                    intent.setComponent(new ComponentName("com.landicorp.android.ebankpay", "com.landicorp.android.ebankpay.MainActivity"));
                    intent.putExtra("transName", "消费");
                    intent.putExtra("amount", price_add + dialog_set_pay_money + "00");
//                    intent.putExtra("amount", "000000000001");
                    startActivityForResult(intent, 300);
                }
            }
        });

        print_jiesuan_ticket.setEnabled(false);

        //结算详情
        getOrderInfo();

        //获取折扣
        getDiscount();
    }


    @OnClick({R.id.back_tv, R.id.vip_score, R.id.coupon_tv, R.id.detailed_tv, R.id.consume_details_tv, R.id.vip_card
            , R.id.print_order_bill, R.id.ali_tv, R.id.wx_tv, R.id.print_jiesuan_ticket, R.id.pay_by_card_tv, R.id.coupon_reset})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_tv:
                if (TextUtils.isEmpty(isPay)) {
                    back_activity();
                }
                break;
            case R.id.vip_score://会员积分
                scren_type = 1;
                newViewBtnClick();
                break;
            case R.id.coupon_tv://优惠券
                scren_type = 2;
                newViewBtnClick();
                break;
            case R.id.detailed_tv://明细
                if (userConponBeans != null && userConponBeans.size() > 0) {
                    couponInfoDialog.showCouponInfoDialog(userConponBeans);
                }
                break;
            case R.id.consume_details_tv://消费明细
                if (orderInfoBean != null && orderInfoBean.order_list != null && orderInfoBean.order_list.size() > 0) {
                    settlementOrderDialog.showSettlementDialog(orderInfoBean);
                }
                break;
            case R.id.vip_card://会员卡
                scren_type = 3;
                newViewBtnClick();
                break;
            case R.id.print_order_bill://打印预结账单
                scren_type = 8;
                getPrint("1");
                break;
            case R.id.ali_tv://支付宝
                scren_type = 4;
                collectionDialog.showCollectionDialog("支付宝", need_pay_last_money_nomoling + "");
                break;
            case R.id.wx_tv://微信
                scren_type = 5;
                collectionDialog.showCollectionDialog("微信", need_pay_last_money_nomoling + "");
                break;
            case R.id.pay_by_card_tv://刷卡
                scren_type = 6;
                collectionDialog.showCollectionDialog("刷卡", need_pay_last_money_nomoling + "");
                break;
            case R.id.print_jiesuan_ticket://打印结算小票
                scren_type = 7;
                getPrint("2");
                break;
            case R.id.coupon_reset://优惠重置
                if (!TextUtils.isEmpty(isPay)) {
                    AtyUtils.showShort(mActivity, "订单已支付，优惠方案不可重置", true);
                } else {
                    getOrderInfo();
                    getDiscount();
                }
                break;
        }
    }

    /**
     * 获取结算详情
     */
    private void getOrderInfo() {
        Map<String, String> params = API.getParams();
        params.put("order_sn", order_sn);
        MyOkHttpUtils.post_CallBack(API.jiesuan, params, API.getHeads(mActivity), new OkHttpSuccessListener(
                (IBaseView) mActivity, "获取结算详情", 2) {
            @Override
            public void onSuccessResponse(String response) {
                if (API.filterJson(response)) {
                    orderInfoBean = JsonTwoUtils.parseJson(response, OrderInfoBean.class).get(0);
                    userConponBeans.clear();
                    if (orderInfoBean != null) {
                        table_num.setText(orderInfoBean.serialnum);
                        table_time.setText(orderInfoBean.createtime);
                        table_price.setText("消费：" + orderInfoBean.order_fee_all + "元");
                        table_people_count.setText(orderInfoBean.person + "/" + orderInfoBean.zhuowei);
                        old_price.setText("原价：" + orderInfoBean.order_fee_all + "元");
                        need_pay_price.setText("应付：" + orderInfoBean.yingfu_money + "元");

                        //应付价
                        need_pay_last_money_nomoling = orderInfoBean.yingfu_money;

                        //会员积分
                        vip_phone.setText("");

                        //抹零
                        remove_zero_tv.setHint("最大抹零上限金额" + orderInfoBean.order_moling + "元");
                        remove_zero_tv.setText("");

                        //优惠券
                        coupon_info_tv.setText("");

                        coupon_price.setText("优惠：" + orderInfoBean.youhui_money + "元");
                        already_pay_price.setText("已支付：" + orderInfoBean.already_money + "元");

                        setUiClickState(1);
                    }
                }
            }

            @Override
            public void onErrorResponse() {
                AtyUtils.showShort(mActivity, "获取结算详情失败", false);
            }
        });
    }

    /**
     * 查询会员信息
     */
    private void searchUserInfo(String phone) {
        Map<String, String> params = API.getParams();
        params.put("phone", phone);
        params.put("order_sn", order_sn);
        params.put("discount_id", discount_id);
        MyOkHttpUtils.post_CallBack(API.get_user_info, params, API.getHeads(mActivity), new OkHttpSuccessListener(
                (IBaseView) mActivity, "查询会员信息", 2) {
            @Override
            public void onSuccessResponse(String response) {
                if (API.filterJson(response)) {
                    CouponUserInfo couponUserInfo = JsonTwoUtils.parseJson(response, CouponUserInfo.class).get(0);
                    if (couponUserInfo != null) {
                        is_member = "1";
                        vip_phone.setText(couponUserInfo.user_point + "");
                        coupon_price.setText("优惠：" + couponUserInfo.youhui_money + "元");
                        need_pay_price.setText("应付：" + couponUserInfo.yingfu_money + "元");
                        need_pay_last_money_nomoling = couponUserInfo.yingfu_money;
                    }
                }
            }

            @Override
            public void onErrorResponse() {
                AtyUtils.showShort(mActivity, "查询会员信息失败", false);
            }
        });
    }

    /**
     * 会员卡支付
     */
    private void vipCardPay(String vip_card_code) {

        jifen_code = vip_card_code;

        Map<String, String> params = API.getParams();
        params.put("phone", vip_card_code);
        params.put("order_sn", order_sn);
        params.put("moling", is_moling ? "" : AtyUtils.getText(remove_zero_tv));
        params.put("price", need_pay_last_money_nomoling + "");
        MyOkHttpUtils.post_CallBack(API.member_pay, params, API.getHeads(mActivity), new OkHttpSuccessListener(
                (IBaseView) mActivity, "会员卡支付", 2) {
            @Override
            public void onSuccessResponse(String response) {
                if (API.filterJson(response)) {
                    payCallbackValueSet(response);
                }
            }

            @Override
            public void onErrorResponse() {
                AtyUtils.showShort(mActivity, "会员卡支付失败", false);
            }
        });
    }

    /**
     * 取消优惠
     */
    private void cancelCoupon(String card_id, final int position) {
        Map<String, String> params = API.getParams();
        params.put("coupon_code", card_id);
        params.put("order_sn", order_sn);
        params.put("discount_id", discount_id);
        MyOkHttpUtils.post_CallBack(API.cancel_coupon, params, API.getHeads(mActivity), new OkHttpSuccessListener(
                (IBaseView) mActivity, "取消优惠", 3) {
            @Override
            public void onSuccessResponse(String response) {
                if (API.filterJson(response)) {
                    UserConponBean userConponBean = JsonTwoUtils.parseJson(response, UserConponBean.class).get(0);

                    coupon_price.setText("优惠：" + userConponBean.youhui_money + "元");
                    need_pay_price.setText("应付：" + userConponBean.yingfu_money + "元");

                    need_pay_last_money_nomoling = userConponBean.yingfu_money;

                    userConponBeans.remove(position);
                    coupon_info_tv.setText("共" + userConponBeans.size() + "张，优惠" + userConponBean.coupon_fee + "元");
                }
            }

            @Override
            public void onErrorResponse() {
                AtyUtils.showShort(mActivity, "取消优惠失败", true);
            }
        });
    }

    /**
     * 优惠券是否可用
     */
    private void couponIsUse(String coupon_id) {
        Map<String, String> params = API.getParams();
        params.put("price", orderInfoBean.order_fee_all);
        params.put("coupon_code", coupon_id);
        params.put("order_sn", order_sn);
        params.put("discount_id", discount_id);
        OkHttpUtils.post()
                .url(API.check_coupon)
                .params(params)
                .headers(API.getHeads(mActivity))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        AtyUtils.showShort(mActivity, "网络异常，请稍后再试", true);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            AtyUtils.i("优惠券是否可用", response);
                            if (API.filterJson(response)) {
                                UserConponBean userConponBean = JsonTwoUtils.parseJson(response, UserConponBean.class).get(0);

                                userConponBeans.add(userConponBean);
                                coupon_price.setText("优惠：" + userConponBean.youhui_money + "元");
                                need_pay_price.setText("应付：" + userConponBean.yingfu_money + "元");

                                need_pay_last_money_nomoling = userConponBean.yingfu_money;

                                coupon_info_tv.setText("共" + userConponBeans.size() + "张，优惠" + userConponBean.coupon_fee + "元");
                            } else {
                                AtyUtils.showShort(mActivity, jsonObject.getString("msg"), false);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 获取折扣方案
     */
    private void getDiscount() {
        MyOkHttpUtils.post_CallBack(API.jiesuan_discount, null, API.getHeads(mActivity), new OkHttpSuccessListener(
                (IBaseView) mActivity, "获取折扣方案", 2) {
            @Override
            public void onSuccessResponse(String response) {
                if (API.filterJson(response)) {
                    discounts.clear();
                    List<OrderInfoDiscountListBean> orderInfoDiscountListBeans = JsonTwoUtils.parseListJson(response, OrderInfoDiscountListBean.class);
                    if (orderInfoDiscountListBeans.size() > 0) {
                        discounts.addAll(orderInfoDiscountListBeans);
                        orderInfoDiscountAdapter.notifyDataSetChanged();
                    } else {
                        order_info_recyclerview.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onErrorResponse() {
                AtyUtils.showShort(mActivity, "获取折扣方案失败", false);
            }
        });
    }

    /**
     * 点击折扣
     *
     * @param position
     */
    @Override
    public void discountClick(int position) {
        if (discounts.get(position).isChecked) {
            discounts.get(position).isChecked = false;
            orderInfoDiscountAdapter.notifyDataSetChanged();
            useDiscount(discounts.get(position).id, 1);
        } else {
            for (int i = 0; i < discounts.size(); i++) {
                discounts.get(i).isChecked = false;
            }
            discounts.get(position).isChecked = true;
            orderInfoDiscountAdapter.notifyDataSetChanged();

            useDiscount(discounts.get(position).id, 0);
        }
    }

    /**
     * 使用折扣
     */
    private void useDiscount(String id, int type) {
        Map<String, String> params = API.getParams();
        params.put("order_sn", order_sn);
        params.put("discount_id", id);
        MyOkHttpUtils.post_CallBack(type == 0 ? API.use_discount : API.cancel_discount, params, API.getHeads(mActivity), new OkHttpSuccessListener(
                (IBaseView) mActivity, "使用折扣", 2) {
            @Override
            public void onSuccessResponse(String response) {
                if (API.filterJson(response)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONObject data = jsonObject.getJSONObject("data");
                        String youhui_money = data.getString("youhui_money");
                        String yingfu_money = data.getString("yingfu_money");
                        discount_id = id;
                        coupon_price.setText("优惠：" + youhui_money + "元");
                        need_pay_price.setText("应付：" + yingfu_money + "元");

                        need_pay_last_money_nomoling = yingfu_money;

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onErrorResponse() {
                AtyUtils.showShort(mActivity, "使用折扣失败", false);
            }
        });
    }

    /**
     * 抹零走接口
     */
    private void Moling(String moling) {
        Map<String, String> params = API.getParams();
        params.put("order_sn", order_sn);
        params.put("moling", moling);
        MyOkHttpUtils.post_CallBack(API.jiezhang_moling, params, API.getHeads(mActivity), new OkHttpSuccessListener(
                (IBaseView) mActivity, "抹零走接口", 2) {
            @Override
            public void onSuccessResponse(String response) {
                if (API.filterJson(response)) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONObject data = jsonObject.getJSONObject("data");
                        String moling = data.getString("moling");
                        String youhui_money = data.getString("youhui_money");
                        String yingfu_moling = data.getString("yingfu_moling");

                        coupon_price.setText("优惠：" + youhui_money + "元");
                        need_pay_price.setText("应付：" + yingfu_moling + "元");

                        need_pay_last_money_nomoling = yingfu_moling;

                        setUiClickState(0);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onErrorResponse() {
                AtyUtils.showShort(mActivity, "抹零失败", false);
            }
        });
    }

    /**
     * 设置控件点击状态。。
     */
    private void setUiClickState(int type) {
        if (orderInfoDiscountAdapter != null) {
            orderInfoDiscountAdapter.setType(type == 0 ? 1 : 0);
            orderInfoDiscountAdapter.notifyDataSetChanged();
        }
        vip_score.setEnabled(type == 0 ? false : true);
        coupon_tv.setEnabled(type == 0 ? false : true);
    }

    /**
     * 支付成功更改页面数据
     */
    private void payCallbackValueSet(String response) {
        isPay = "1";
        setUiClickState(0);
        VipCardPayBean vipCardPayBean = JsonTwoUtils.parseJson(response, VipCardPayBean.class).get(0);

        if (vipCardPayBean != null) {
            need_pay_last_money_nomoling = vipCardPayBean.alance;
            already_pay_price.setText("已支付：" + vipCardPayBean.paid + "元" + "\n还需支付：" + vipCardPayBean.alance + "元");
            is_moling = vipCardPayBean.is_moling;

            if (is_moling) {
                setCanNotEditNoClick(remove_zero_tv);
            }

            AtyUtils.showShort(mActivity, "支付成功", false);
            if (!TextUtils.isEmpty(vipCardPayBean.alance) && vipCardPayBean.alance.equals("0")) {//还需支付金额为0，说明这个订单支付成功
                print_jiesuan_ticket.setEnabled(true);

                new SearchHistoryDeleteDialog(mActivity).showHintDialog2("取消", "确定", "", "是否打印小票"
                        , new DefaultHintDialogListener() {

                            @Override
                            public void clickConfirmButton() {
                                isOrderFinish = true;
                                scren_type = 7;
                                getPrint("2");
                            }

                            @Override
                            public void clickCancelButton() {
                                back_activity();
                            }
                        });
            }
        }
    }

    /**
     * 获取打印数据
     * type 1结账  2预结账
     */
    private void getPrint(String type) {
        Map<String, String> params = API.getParams();
        params.put("order_sn", order_sn);
        params.put("type", type);
        MyOkHttpUtils.post_CallBack(API.print_receipt, params, API.getHeads(mActivity), new OkHttpSuccessListener(
                (IBaseView) mActivity, "获取打印数据", 2) {
            @Override
            public void onSuccessResponse(String response) {
                if (API.filterJson(response)) {
                    List<Object> objects = JsonTwoUtils.parseListJson(response, Object.class);
                    if (objects != null) {
                        printer_templete.clear();
                        printer_templete.addAll(objects);
                    }
                    if (PrintUtils.canSupport(Constants.ModelSupport.SUPPORT_MODEL_ALL, mActivity)) {
                        newViewBtnClick();
                    }
                    if (isOrderFinish) {
                        back_activity();
                    }
                }
            }

            @Override
            public void onErrorResponse() {
                AtyUtils.showShort(mActivity, "打印失败", false);
            }
        });
    }

    /**
     * 退款
     */
    private void refundMoney(final String value) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    int numcode = (int) ((Math.random() * 9 + 1) * 100000);
                    long startTime = System.currentTimeMillis();

                    HmpayClient hmpayClient = new HmpayClient(Constant.url);

                    TradeRequest tradeRequest = TradeRequest.builder()
                            .appId(Constant.appId)
                            .subAppId(Constant.subAppId)
                            .format("JSON")
                            .method("trade.refund")
                            .signType("RSA")
                            .timestamp(DateUtils.getNowDate1(new Date()))
                            .nonce(numcode + "")
                            .version("1.0")
                            .bizContent(TradeRefundRequest.builder()
                                    .refundRequestNo(startTime + numcode + "")
                                    .refundAmount(Double.parseDouble(dialog_set_pay_money))
                                    .bankOrderNo(value)
                                    .build()
                                    .toJsonString()
                            )
                            .build()
                            .buildSign(Constant.privateKey);

                    TradeResponse tradeResponse = hmpayClient.execute(tradeRequest);

                    AtyUtils.i("请求结果：", tradeResponse.toString());
                    long endTime = System.currentTimeMillis();
                    AtyUtils.i("花费时间: ", (endTime - startTime) + "ms");
                    boolean b = RsaUtil.rsaCheckV2(tradeResponse.toMap(), Constant.platPublicKey, TradeContants.CHARSET);
                    AtyUtils.i("验签结果：", b + "");
                } catch (Exception e) {
                    e.printStackTrace();
                    show("退款异常");
                }
            }
        }).start();
    }

    /**
     * 河马支付
     *
     * @param value
     */
    private void hemapay(String value) {

//        try {
//            AtyUtils.i("ip地址", IpCreateUtils.getIP(mActivity));
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("order_sn", order_sn);
//            jsonObject.put("device_id", API.getDeviceID(mActivity));
//
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    int money = (int) dialog_set_pay_money;
//                    double pay_money = money;
//
//                    int numcode = (int) ((Math.random() * 9 + 1) * 100000);
//                    long startTime = System.currentTimeMillis();
//
//                    HmpayClient hmpayClient = new HmpayClient(url);
//
//                    TradeRequest tradeRequest = TradeRequest.builder()
//                            .appId(appId)
//                            .subAppId(subAppId)
//                            .format("JSON")
//                            .charset("UTF-8")
//                            .method("trade.pay")
//                            .signType("RSA")
//                            .timestamp(DateUtils.getNowDate1(new Date()))
//                            .nonce(numcode + "")
//                            .version("1.0")
//                            .bizContent(TradePayRequest.builder()
//                                    .body("商品")
//                                    .createIp(IpCreateUtils.getIP(mActivity))
//                                    .notifyUrl("http://www.moshisushi.cn/api.php/notify_hemapay/notify")
//                                    .outOrderNo(startTime + "" + numcode)
//                                    .storeId(storeId)
//                                    .totalAmount(0.01)
//                                    .authCode(value)
////                                    .reqReserved(jsonObject.toString())
//                                    .build()
//                                    .toJsonString())
//                            .build()
//                            .buildSign(privateKey);
//
//                    TradeResponse tradeResponse = hmpayClient.execute(tradeRequest);
////
//                    AtyUtils.i("请求结果：", tradeResponse.toString());
////                    if (tradeResponse != null) {
////                        if (scren_type == 4) {//支付宝
////                            if (tradeResponse.getCode().equals("200")) {
////                                String data = tradeResponse.getData();
////                                if (!TextUtils.isEmpty(data)) {
////                                    try {
////                                        JSONObject jsonObject = new JSONObject(data);
////                                        if (jsonObject.getString("sub_code").equals("SUCCESS")) {
//////                                            back_activity();
////                                        }
////                                        show(jsonObject.getString("sub_msg"));
////                                    } catch (JSONException e) {
////                                        e.printStackTrace();
////                                    }
////                                }
////                            }
////                        } else if (scren_type == 5) {//微信
////
////                        }
////                    }
//                    long endTime = System.currentTimeMillis();
//                    AtyUtils.i("花费时间: ", (endTime - startTime) + "ms");
//                    boolean b = RsaUtil.rsaCheckV2(tradeResponse.toMap(), platPublicKey, TradeContants.CHARSET);
//                    AtyUtils.i("验签结果：", b + "");
//                }
//            }).start();
//        } catch (Exception e) {
//            e.printStackTrace();
////            AtyUtils.showShort(mActivity, "支付异常", true);
//        }
        showLoading("支付中...");
        Map<String, String> params = API.getParams();
        params.put("input_price", dialog_set_pay_money);
        params.put("device_id", API.getDeviceID(mActivity));
        params.put("pay_code", value);
        params.put("user_card", jifen_code);
        params.put("order_sn", order_sn);
        params.put("moling", is_moling ? "" : AtyUtils.getText(remove_zero_tv));
        params.put("price", need_pay_last_money_nomoling);

        OkHttpUtils.post()
                .url(API.pay_sand_code)
                .params(params)
                .headers(API.getHeads(mActivity))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        dismissLoading();
                        AtyUtils.showShort(mActivity, "扫码支付失败", false);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        dismissLoading();
                        AtyUtils.i("河马支付", response);
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (jsonObject.getInt("code") == 200) {
                                payCallbackValueSet(response);
                            } else if (jsonObject.getInt("code") == 201) {
                                AtyUtils.showShort(mActivity, jsonObject.getString("msg"), false);
                                if (dialog_set_pay_money.equals(need_pay_last_money_nomoling)) {//说明用户支付成功后就支付完毕
                                    new SearchHistoryDeleteDialog(mActivity).showHintDialog2("取消", "确定", "", "是否打印小票"
                                            , new DefaultHintDialogListener() {

                                                @Override
                                                public void clickConfirmButton() {
                                                    isOrderFinish = true;
                                                    scren_type = 7;
                                                    getPrint("2");
                                                }

                                                @Override
                                                public void clickCancelButton() {
                                                    back_activity();
                                                }
                                            });
                                }
                            } else {//支付失败或者非付款码
                                AtyUtils.showShort(mActivity, jsonObject.getString("msg"), false);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 吐司
     *
     * @param msg
     */
    public void show(String msg) {
        //解决在子线程中调用Toast的异常情况处理
        Looper.prepare();
        AtyUtils.showShort(mActivity, msg, false);
        Looper.loop();
    }

    /**
     * 根据手机版本判断操作
     */
    public void newViewBtnClick() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.requestPermissions(
                    new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.VIBRATE, Manifest.permission.READ_PHONE_STATE},
                    DEFAULT_VIEW);
        } else {
            if (scren_type == 7 || scren_type == 8) {
                if (printer_templete != null && printer_templete.size() > 0) {
                    presenter.start(printer_templete);
                }
            } else {
                //开始扫描条形码的ScankitActivity
                ScanUtil.startScan(SettlementActivity.this, REQUEST_CODE_SCAN, new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.ALL_SCAN_TYPE).create());
            }
        }

    }


    //华为扫码：https://www.cnblogs.com/developer-huawei/p/12834798.html
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (permissions == null || grantResults == null || grantResults.length < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        if (requestCode == DEFAULT_VIEW) {
            if (scren_type == 7 || scren_type == 8) {
                if (printer_templete != null && printer_templete.size() > 0) {
                    presenter.start(printer_templete);
                }
            } else {
                //开始扫描条形码的ScankitActivity
                ScanUtil.startScan(SettlementActivity.this, REQUEST_CODE_SCAN, new HmsScanAnalyzerOptions.Creator().setHmsScanTypes(HmsScan.ALL_SCAN_TYPE).create());
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        try {
            switch (resultCode) {
                case Activity.RESULT_CANCELED: //交易失败
                    String reason = data.getStringExtra("reason");
                    if (!TextUtils.isEmpty(reason)) {
                        AtyUtils.showShort(mActivity, reason, false);
                    }
                    break;
                case Activity.RESULT_OK: //在您的活动完成扫描后接收结果
                    // 从onActivityResult方法返回的值中获取HmsScan的返回值，方法是扫描util.RESULT作为键值。
                    if (requestCode == REQUEST_CODE_SCAN) {
                        Object obj = data.getParcelableExtra(ScanUtil.RESULT);
                        if (obj instanceof HmsScan) {
                            if (!TextUtils.isEmpty(((HmsScan) obj).getOriginalValue())) {
                                String originalValue = ((HmsScan) obj).getOriginalValue();
                                AtyUtils.i("扫码数据", originalValue);
                                switch (scren_type) {
                                    case 1://查询积分
                                        searchUserInfo(originalValue);
                                        break;
                                    case 2://验证优惠券
                                        couponIsUse(originalValue);
                                        break;
                                    case 3://会员卡支付
                                        vipCardPay(originalValue);
                                        break;
                                    case 4://支付宝扫码支付
                                        hemapay(originalValue);
//                                    refundMoney(originalValue);
                                        break;
                                    case 5://微信扫码支付
                                        hemapay(originalValue);
                                        break;
                                }
                            }
                            return;
                        }
                    } else if (requestCode == 300) {
                        AtyUtils.showShort(mActivity, "支付成功", false);
                        String amount = data.getStringExtra("amount");
                        String traceNo = data.getStringExtra("traceNo");
                        String referenceNo = data.getStringExtra("referenceNo");
                        String cardNo = data.getStringExtra("cardNo");

                        String issue = data.getStringExtra("issue");
                        String batchNo = data.getStringExtra("batchNo");
                        String terminalId = data.getStringExtra("terminalId");
                        String merchantId = data.getStringExtra("merchantId");
                        String merchantName = data.getStringExtra("merchantName");

                        String date = data.getStringExtra("date");
                        String time = data.getStringExtra("time");
                        String marketCardInfo = data.getStringExtra("marketCardInfo");
                        payCardCallBack(amount, cardNo, date, time, traceNo, referenceNo, issue, batchNo, terminalId, merchantId, merchantName, marketCardInfo);
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();

            AtyUtils.i("扫码数据", "异常" + e.toString());
        }
    }

    /**
     * 刷卡完成通知服务端写入
     */
    private void payCardCallBack(String amount, String cardNo, String date, String time, String traceNo, String referenceNo, String issue, String batchNo
            , String terminalId, String merchantId, String merchantName, String marketCardInfo) {
        Map<String, String> params = API.getParams();
        params.put("amount", amount);
        params.put("cardNo", cardNo);
        params.put("date", date);
        params.put("time", time);
        params.put("traceNo", traceNo);
        params.put("referenceNo", referenceNo);
        params.put("issue", issue);
        params.put("batchNo", batchNo);
        params.put("terminalId", terminalId);
        params.put("merchantId", merchantId);
        params.put("merchantName", merchantName);
        params.put("marketCardInfo", marketCardInfo);

        params.put("order_sn", order_sn);
        params.put("moling", is_moling ? "" : AtyUtils.getText(remove_zero_tv));
        params.put("price", need_pay_last_money_nomoling + "");

        AtyUtils.i("扫码数据", params.toString());
        MyOkHttpUtils.post_CallBack(API.pay_card_write, params, API.getHeads(mActivity), new OkHttpSuccessListener(
                (IBaseView) mActivity, "刷卡完成通知服务端写入", 2) {
            @Override
            public void onSuccessResponse(String response) {
                if (API.filterJson(response)) {
                    payCallbackValueSet(response);
                }
            }

            @Override
            public void onErrorResponse() {
//                AtyUtils.showShort(mActivity, "刷卡完成通知服务端写入失败", true);
            }
        });
    }


    /**
     * 设置不可编辑且无点击事件
     *
     * @param view
     */
    public void setCanNotEditNoClick(EditText view) {
        view.setFocusable(false);
        view.setFocusableInTouchMode(false);
        // 如果之前没设置过点击事件，该处可省略
        view.setOnClickListener(null);
    }


    /**
     * 设置点击软键盘之外区域，软键盘消失
     *
     * @param view
     */
    public void setHintKeyboardView(View view) {
        if (!(view instanceof EditText)) {
            view.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    hideSoftKeyboard();
                    return false;
                }
            });
        }
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View innerView = ((ViewGroup) view).getChildAt(i);
                setHintKeyboardView(innerView);
            }
        }
    }


    /**
     * 退出程序
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (TextUtils.isEmpty(isPay)) {
                back_activity();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 关闭页面
     */
    private void back_activity() {
        setResult(101);
        finish();
    }

    protected LocalBroadcastManager broadcastManager;
    protected IntentFilter intentFilter;
    protected SettlementReceiver receiver;

    /**
     * 通知消息
     */
    public static final String ACTION_RECIVE_NEWRED = "settle_action_awaiter";

    /**
     * 支付回调广播监听
     */
    public class SettlementReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                try {
                    String action = intent.getAction();
                    String extra = intent.getStringExtra("extra");
                    if (TextUtils.equals(action, ACTION_RECIVE_NEWRED)) {
                        dismissLoading();

                        payCallbackValueSet(extra);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        bindDeviceService();
        presenter = new PrinterPresenterImpl(this);
    }

    // Sometimes you need to release the right of using device before other application 'onStart'.
    @Override
    protected void onPause() {
        super.onPause();
        unbindDeviceService();
    }

    @Override
    protected void onDestroy() {
        // 广播监听
        if (broadcastManager != null && receiver != null) {
            broadcastManager.unregisterReceiver(receiver);
        }

        super.onDestroy();
    }

}
